﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using System.Web;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// TMS运单价格分摊
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMSPrice_ApportionController : ControllerBase
    {
        private readonly ILogger<TMSPrice_ApportionRequestDto> _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;


        public TMSPrice_ApportionController(ILogger<TMSPrice_ApportionRequestDto> logger,IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration)
        {
            _logger = logger;
            _WMSTokenCheckService = wmsTokenCheckService;
             con= _configuration.GetConnectionString("DDM_DbConnection_ZH");

        }

        /// <summary>
        /// TMS运单价格分摊
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostTMSPrice_Apportion([FromBody] TMSPrice_ApportionRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            TMSPrice_ApportionResponseDto re = new TMSPrice_ApportionResponseDto();
            string shippingorderno = strparm.shippingorderno;
            string sysid = "";
            if (shippingorderno.Trim()=="")
            {
                sysid = "TMS0011";
            }
            else
            {
                sysid = "TMS0009";
            }



            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
                dic.Add("shippingorderno", shippingorderno);//查看URL配置表地址描述
                DataTable dt_shippingorder = MethodHelp.GetTableInfo(sysid, dic, con);//运单列表
                if (dt_shippingorder.Rows.Count>0)
                {
                    foreach (DataRow item in dt_shippingorder.Rows)
                    {
                        decimal qty = DB.ToDecimal(item["shipment_amount"].ToString());
                        dic = new Dictionary<string, string>();
                        dic.Add("shippingorderno", item["shippingorderno"].ToString());//查询运单销售明细
                        DataTable dt_shippingorder_d = MethodHelp.GetTableInfo("TMS0008", dic, con);//运单明细
                        if (dt_shippingorder_d.Rows.Count>0)
                        {
                            int i = 0;
                            decimal zb = 0;
                            decimal pl = 0;
                            strSqlList = new List<string>();
                            foreach (DataRow row in dt_shippingorder_d.Rows)
                            {
                                i++;
                                decimal quantity_ratio = Math.Round(DB.ToDecimal(row["shipment_amount"].ToString())/ qty, 3);
                                decimal price_share = Math.Round(DB.ToDecimal(row["cprice"].ToString())* quantity_ratio,3);
                                zb = zb + quantity_ratio;
                                pl = pl + price_share;

                                if (i== dt_shippingorder_d.Rows.Count)
                                {
                                    if (zb!=1|| pl!= DB.ToDecimal(row["cprice"].ToString()))
                                    {
                                        quantity_ratio = Math.Round(1 - (zb - quantity_ratio),3);
                                        price_share = Math.Round(DB.ToDecimal(row["cprice"].ToString()) - (pl - price_share),3);
                                    }
                                }
                                dic = new Dictionary<string, string>();
                                dic.Add("price_share", price_share.ToString());//价格分摊
                                dic.Add("quantity_ratio", quantity_ratio.ToString());//数量占比
                                dic.Add("id", row["autoid"].ToString());//查询运单销售明细
                                string strSQL = MethodHelp.GetTranSQL("TMS0010", dic, con);//转换插入任务执行明细表SQL语句
                                if (strSQL == "")
                                {
                                    strMsg = "TMS0010,Parameter conversion failed";
                                }
                                else
                                {
                                    strSqlList.Add(strSQL.ToString());
                                }

                                
                            }
                            if (strSqlList.Count>0)
                            {
                                bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                            }
                        }

                    }
                }


            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

         


            if (strMsg=="")
            {
                re.code = 0;
               
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }


            return new JsonResult(re);
        }

      
    }
}
